package com.zzyl.common.test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class QianfanApiService {

    private final RestTemplate restTemplate;
    private static final String API_URL = "https://qianfan.baidubce.com/v2/chat/completions";
    private static final String AUTH_TOKEN = "bce-v3/ALTAK-Hq1PnSSh7UZydfAUlF0hg/ad8de287a6989e0c729dce9483191ffb67191840"; // 替换为你的实际token


    // 构造函数注入RestTemplate
    public QianfanApiService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    /**
     * 调用百度千帆大模型API
     * @param userMessage 用户消息内容
     * @return API返回的响应结果
     */
    public String callQianfanApi(String userMessage) {
        // 创建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + AUTH_TOKEN);

        // 构建请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", "ernie-3.5-8k");

        // 构建消息列表
        List<Map<String, String>> messages = new ArrayList<>();

        // 系统消息
        Map<String, String> systemMessage = new HashMap<>();
        systemMessage.put("role", "system");
        systemMessage.put("content", "平台助手");
        messages.add(systemMessage);

        // 用户消息
        Map<String, String> userMsg = new HashMap<>();
        userMsg.put("role", "user");
        userMsg.put("content", userMessage);
        messages.add(userMsg);

        requestBody.put("messages", messages);

        // 创建HttpEntity对象封装请求头和请求体
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);

        // 发送POST请求并获取响应
        ResponseEntity<String> response = restTemplate.postForEntity(
                API_URL,
                requestEntity,
                String.class
        );

        // 返回响应体
        return response.getBody();
    }

    public static void main(String[] args) {
        QianfanApiService qianfanApiService = new QianfanApiService(new RestTemplate());
        String string = qianfanApiService.callQianfanApi("今天的天气怎么样");
        System.out.println(string);
    }
}

